package StringDemo;

/**
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * 如果不存在公共前缀，返回空字符串 ""。
 */
public class demo14 {
    public static void main(String[] args) {
        System.out.println(longestCommonPrefix(new String[]{"flower","flow","flight"}));
        System.out.println(longestCommonPrefix(new String[]{"dog","racecar","car"}));
    }
    public static String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        for (int index = 0; index < strs[0].length(); index++) {
            char st = strs[0].charAt(index);
            for (int i = 1; i < strs.length; i++) {
                if(index+1>strs[i].length()){
                    return strs[0].substring(0, index);
                }
                if (strs[i].charAt(index) == st && index < strs[i].length()) {
                } else {
                    return strs[0].substring(0, index);
                }
            }
        }
        return strs[0];
    }
}
